package control

import (
	"Sales_system/Dao"
	"Sales_system/pkg/app"
	"Sales_system/pkg/e"
	"Sales_system/services"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func Getconsumer(c *gin.Context)  {
	err, info, total := services.Getallconsumer()
	//fmt.Println(info);
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total},"OK")
}

func Addconsumer(c *gin.Context)  {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	if m["consumer_id"] == ""{
		app.INFO(c, 30000, "参数非法")
		return
	}

	new_consumer := Dao.Consumer{
		Consumer_id: com.StrTo(m["consumer_id"]).MustInt(),
		Consumer_name: m["consumer_name"],
		Consumer_address:m["consumer_address"],
		Consumer_postcode: m["consumer_postcode"],
		Consumer_phone: m["consumer_phone"],
		//Is_del: com.IsDir(m["is_del"]),
	}
	err := services.Addconsumer(new_consumer)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"添加成功")
}


func Updateconsumer(c *gin.Context){
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	if m["consumer_id"] == ""{
		app.INFO(c, 30000, "参数非法")
		return
	}

	new_consumer := Dao.Consumer{
		Consumer_id: com.StrTo(m["Consumer_id"]).MustInt(),
		Consumer_name: m["Consumer_name"],
		Consumer_address:m["Consumer_address"],
		Consumer_postcode: m["Consumer_postcode"],
		Consumer_phone: m["Consumer_phone"],
		//Is_del: com.IsDir(m["is_del"]),
	}

	err := services.Updateconsumer(new_consumer)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}
	app.OK(c, map[string]interface{}{},"更新成功")
}



func Delconsumer(c *gin.Context){
	var id = ""
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	id = m["Consumer_name"]
	if id == ""{
		app.INFO(c,30001,"参数错误")
		return
	}

	err := services.Deleteconsumer(id)
	if err !=nil{
		app.Error(c,e.ERROR,err,err.Error())
		return
	}

	app.OK(c, map[string]interface{}{},"删除成功")
}